var express = require('express');
var router = express.Router();
const { Chapter,Course,Category,User } = require('../models');
const { NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {
        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;
        
        if (!query.courseId) {
            throw new Error('获取章节列表失败，课程ID不能为空')
        }

        const condition = {
            ...getCondition(),
            order: [['rank', 'ASC'],['id', 'ASC']],
            offset: offset,
            limit: pageSize
        }
        condition.where = {
            courseId: {
                [Op.eq]: query.courseId
            }
        }
        if (query.title) {
            condition.where.title = {
                [Op.like]: `%${query.title}%`
            }
        }
        const { count, rows } = await Chapter.findAndCountAll(condition);
        success(
            res,
            '查询章节列表成功',
            {
                chapter: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询章节详情
router.get('/:id', async function (req, res, next) {
    try {
        const chapter = await getChapter(req);
        // 查询 courseId 课程下的所有章节（章节列表是给目录使用的）
        chapters = await Chapter.findAll({
            attributes: { exclude: ['CourseId', 'content'] },
            where: { courseId: chapter.courseId },
            order:[['rank', 'ASC'],['id','DESC']]
        })
        success(
            res,
            '查询章节成功',
            {chapter,chapters}
        )

    } catch (error) {
        failure(res, error)
    }
});




/**
 * 查询当前章节
 * @param {*} req 
 */
async function getChapter(req) {
    const { id } = req.params;
    const condition = getCondition();
    const chapter = await Chapter.findByPk(id,condition);
    if (!chapter) {
        throw new NotFoundError(`ID: ${id}的章节未找到`)
    }
    return chapter;
}

/** 公共方法：关联课数据 */
const getCondition = () => {
    return {
        attributes: { exclude: ['CourseId'] },
        include: [
            {
                model: Course, as: 'course', attributes: ['id', 'name'],
                include: [
                    {
                        model: User, as: 'user',
                        attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
                    }
                ]
            },
        ]
    }
}

module.exports = router;
